#include <stdio.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <time.h>

#include "game.h"
#include "inet.h"
#include "../update/proc.h"

extern uint8_t q_map[WIDTH_AREA][HEIGHT_AREA];
extern uint32_t num_players;
extern FILE *log_file;
extern int max_fd;
extern fd_set master;

int main (int argc, char *argv[])
{
    struct sockaddr_in addr;
    crd_t player_crd;

    int8_t ret;
    uint32_t frame_delay = 300;
    uint32_t port = 2229;

    fd_set read_fds;
    struct timespec fr_d;
    mess_t message;
    uint8_t direction;

    num_players = 4;
    log_file = stderr;

    while ((ret = getopt(argc, argv, "hf:d:n:p:")) != -1)
    {
        switch (ret)
        {
            case 'h':
                printf("%s", HELP_SERVER);
                exit(EXIT_SUCCESS);
            break;

            case 'f':
                log_file = fopen(optarg, "w");                
            break;

            case 'd':
                frame_delay = atoi(optarg);
            break;

            case 'n':
                num_players = atoi(optarg);
            break;

            case 'p':
                port = atoi(optarg);
            break;
        }
    }

    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(port);

    srand((unsigned)time(0x0));
    player_crd = create_qmap();

    init_server(&addr);
    wait_clients();
    start_game(frame_delay, player_crd);

    fr_d.tv_nsec = frame_delay*1000000;
    fr_d.tv_sec = 0;

    setbuf(log_file, NULL);
    while (1)
    {
        FD_ZERO(&read_fds);
        read_fds = master;

        Pselect(max_fd+1, &read_fds, &fr_d);

        for (int fd = 0; fd <= max_fd; ++fd)
        {
            if (FD_ISSET(fd, &read_fds))
            {
                if (Recv(fd, &message, sizeof(mess_t), 0) == 0)
                {
                    disconnect(fd);
                    continue;
                }

                message.magic = ntohl(message.magic);
                message.ptype = ntohl(message.ptype);
                message.datasize = ntohl(message.datasize);
                
                if (message.magic != MAGIC || message.ptype != 0x00)
                {
                    disconnect(fd);
                    continue;
                }
                
                if (Recv(fd, &direction, 1, 0) == 0)
                {
                    disconnect(fd);
                    continue;
                }

                // if (Recv(fd, player_name, message.datasize - 1, 0) == 0)
                // {
                //     disconnect(fd);
                //     continue;
                // }
                
                // player_name[message.datasize - 1] = '\0';
                fprintf(log_file, "[SERVER] Player '%s' change direction: %d\n",
                                    fd_to_name(fd), direction);
                send_new_state(fd, direction);

            }
        }
    }
}
